namespace :website do
  desc "Backup website"
  task :backup do
    on roles(:db) do |host|
      within current_path do
        with rack_env: fetch(:rails_env) do
          dirname = Time.now.strftime('%Y%m%d%H%M%S')
          rake "db:data:dump_dir dir=backups/#{dirname}"
          execute :cp, "-r #{shared_path}/public/system db/backups/#{dirname}"
          execute :tar, "-zcf /tmp/backup.tar.gz db/backups/#{dirname}"
          download! "/tmp/backup.tar.gz", "db/backups/#{fetch(:stage)}-#{host}-#{dirname}.tar.gz"
        end
      end
    end
  end

  task :download, [:dir] do |t, args|
    on roles(:db) do |host|
      within current_path do
        with rack_env: fetch(:rails_env) do
          dirname = args[:dir]
          execute :tar, "-zcf /tmp/backup.tar.gz db/backups/#{dirname}"
          download! "/tmp/backup.tar.gz", "db/backups/#{fetch(:stage)}-#{host}-#{dirname}.tar.gz"
        end
      end
    end
  end

  desc "Restore website"
  task :restore, [:dir] do |t, args|
    on roles(:db) do |host|
      within current_path do
        with rack_env: fetch(:rails_env) do
          tarname = args[:dir]
          dirname = tarname.split("-").last
          upload! "db/backups/#{tarname}.tar.gz", "/tmp/backup.tar.gz"
          execute :tar, "-zxf /tmp/backup.tar.gz"
          execute :mv, "db/backups/#{dirname}/system #{shared_path}/public"
          rake "db:data:load_dir dir=backups/#{dirname}"
        end
      end
    end
  end
end
